package com.benshou.bcss.common.db;

import com.benshou.bcss.common.j17common.annotation.NotNull;
import com.github.yulichang.base.MPJBaseMapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import org.apache.ibatis.session.ExecutorType;

import java.util.function.Function;

/**
 * 基类：数据访问对象
 *
 * @author <a href="mailto:liuzhenbang@benshou.com">Liu Zhenbang</a>
 */
public class BaseDAO<M extends MPJBaseMapper<T>, T> extends MPJBaseServiceImpl<M, T> {

    /**
     * 以 BATCH 模式执行数据操作
     *
     * @param batchOperation 批量操作，其返回 true 时，才会执行提交
     * @return 是否操作成功
     */
    protected boolean executeMapperOperationBatch(@NotNull Function<M, @NotNull Boolean> batchOperation) {
        // BATCH 模式
        try (var sqlSession = getSqlSessionFactory().openSession(ExecutorType.BATCH)) {
            // 获取 mapper 执行批量操作
            var mapper = sqlSession.getMapper(getMapperClass());
            boolean isOperationSuccess;
            try {
                isOperationSuccess = batchOperation.apply(mapper);
            } catch (Exception e) {
                sqlSession.rollback();
                throw e;
            }

            // 根据是否成功决定 提交 or 回滚
            if (isOperationSuccess) {
                sqlSession.commit();
            } else {
                sqlSession.rollback();
            }

            return isOperationSuccess;
        }
    }
}
